import { useEffect, useRef } from 'react';

/*/**
 * 防抖
 * @param func 回调函数
 * @param delay 延迟 默认200秒
 * @param immediate 是否立即执行，默认是
 * @returns
 */
const useDebounce = (func, delay = 200, immediate = true) => {
  const timerRef: any = useRef(null);

  useEffect(() => {
    return () => {
      clearTimeout(timerRef.current);
    };
  }, []);

  const handler = (...args) => {
    clearTimeout(timerRef.current);

    if (immediate) {
      const callNow = !timerRef.current;
      timerRef.current = setTimeout(() => {
        timerRef.current = null;
      }, delay);
      if (callNow) {
        func(...args);
      }
    } else {
      timerRef.current = setTimeout(() => {
        func(...args);
      }, delay);
    }
  };

  return handler;
};

export { useDebounce };
